const express=require('express');
const mysql=require('mysql');
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session');
const urlobj=require('url');
//引用自定义
//const commte=require('../../libs/commtle');
//链接数据库
var db=mysql.createPool({
    host:'localhost',
    user:'root',
    password:'',
    database:'leasedb'
});
//========================
//业务逻辑
module.exports = function() {
    var router = express.Router();
    router.post('/index.html',function(req,res,next){
    db.query("SELECT * FROM admininfo WHERE adminName='"+req.body.adminuername+"'",function (err,data) {
            if(err)
            {
                res.status(500).send('<script>alert("用户名出错了!");window.location.href="login.html";</script>').end();
            }else
            {
                if(data.length==0)
                {
                    res.status(500).send('<script>alert("用户名不存在");window.location.href="login.html";</script>').end();
                }else
                {
                    db.query("SELECT * FROM `admininfo` WHERE adminName='"+req.body.adminuername+"' and adminPwd='"+req.body.adminuerpwd+"'",function(err,data) {

                        if (err)
                        {
                            res.status(500).send('<script>alert("出错了!");window.location.href="404.html";</script>').end();
                        }else
                        {
                            if(data.length==0)
                            {
                                res.status(500).send('<script>alert("密码错误！");</script>').end();
                            }else
                            {
                                console.log(data);
                                //登陆ok存储用户id
                                // req.session['userId']=data[0].userId;
                                // res.redirect('web/index.html');
                                req.session['userId']=data[0].adminId;
                                res.status(500).send('<script>alert("登陆成功!");window.location.href="index.html";</script>').end();
                            }
                            next();
                        }
                    })
                }
            }

    }) ;
    });
    //开始渲染后台首页
    router.get('/login.html',function(req,res,next){
        res.render("admin/login.ejs");
    });
    return router;
}